const router = require('koa-router')()
const jwt = require('jsonwebtoken');
const { secret } = require('../config/config')
const { getToken, getChatId, sendMsg, getOpenId, sendTask } = require('../api/api');
const UserModel = require('../models/UserModel');
// 登录操作
router.post('/login', async (ctx, next) => {
  let { phone, password } = ctx.query
  // 数据库内检索
  const findRes = await UserModel.findOne({ phone: phone })
  if (findRes.password == password) {
    let payload = {
      password,
      time: new Date().getTime(),
      timeout: 1000 * 60 * 60 * 24
    }
    let token = jwt.sign(payload, secret)
    ctx.status = 200
    ctx.body = {
      message: '登陆成功',
      token: token,
    }
  }
})

// 发送信息
router.post('/sendMsg', async (ctx, next) => {
  await getToken().then((result) => {
    if (result.data.code == 0) {
      ctx.status = 200
      let token = "Bearer " + result.data.tenant_access_token
      // 获取机器人所在群组id
      getChatId(token).then((res) => {
        if (res.data.code == 0) {
          // 获取成功
          let { chat_id } = res.data.data.items[0]
          let query = ctx.query
          // 定时发送的定时器
          let timer = null
          timer = setInterval(() => {
            let time = new Date().getTime()
            if (time > query.value) {
              sendMsg(token, chat_id, query)
              clearInterval(timer)
            }
          }, 1000);
        }
      })
    }
  }).catch(error => {
    return ctx.body = {
      msg: error
    }
  })
  ctx.body = {
    msg: '发送成功',
  }
})

// 获取open_id
router.post('/getid', async (ctx, next) => {
  let rtndata, token, phone
  await getToken().then((result) => {
    if (result.data.code == 0) {
      ctx.status = 200
      token = "Bearer " + result.data.tenant_access_token
      phone = ctx.query.phone
    } else {
      ctx.status = 400
      ctx.body = {
        msg: '失败'
      }
    }
  })
  await getOpenId(token, phone).then(res => {
    rtndata = res.data
  })
  ctx.body = {
    msg: '发送成功!',
    data: rtndata
  }
})

// 创建任务
router.post('/sendtask', async (ctx, next) => {
  // console.log(ctx.request.body);
  let token
  await getToken().then((result) => {
    if (result.data.code == 0) {
      ctx.status = 200
      token = "Bearer " + result.data.tenant_access_token
      sendTask(token, ctx.request.body)
    } else {
      ctx.status = 400
      ctx.body = {
        message: 'error'
      }
    }
  })
  ctx.body = {
    msg: '创建任务成功'
  }
})

module.exports = router
